package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.MemberDao;
import com.itheima.pojo.Member;
import com.itheima.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author 黑马程序员
 * @Company http://www.ithiema.com
 * @Version 1.0
 */
@Service
public class MemberServiceImpl implements MemberService {

    @Autowired
    MemberDao memberDao;

    /**
     * 步骤：
     *   1. 判断是否是会员，如果是会员，直接返回
     *   2. 如果不是会员，自动注册为会员
     *
     * @param map
     */
    @Override
    public Member handleMember(Map<String, String> map) {
        String telephone = map.get("telephone");
        //通过手机号码判断会员是否存在
        Member member = memberDao.findByTelephone(telephone);
        if(member == null){
            //创建会员对象
            member = new Member();
            //手机号码
            member.setPhoneNumber(telephone);
            //设置档案编号 == 年月日时分秒+ 随机数
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
            String fileNumber = sdf.format(new Date()) + ValidateCodeUtils.generateValidateCode(4);

            member.setFileNumber(fileNumber);
            member.setRegTime(new Date());

            memberDao.add(member);
        }
        return member;
    }

    @Override
    public Member findById(Integer id) {
        return memberDao.findById(id);
    }

    @Override
    public void edit(Member member) {
        memberDao.edit(member);
    }

    /**
     {
         month: ['2019-01','2019-02']
         meberCount:[20,100]
         }

     *
     * @return
     */
    @Override
    public Map<String, Object> getMemberReport() {
        //创建集合包含12个月份
        List<String> months = new ArrayList<>();
        //日历对象
        Calendar calendar = Calendar.getInstance();
        //向前移动12个月
        calendar.add(Calendar.MONTH, -12);
        for (int i = 0; i < 12; i++) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM");
            String str = simpleDateFormat.format(calendar.getTime());
            months.add(str);
            calendar.add(Calendar.MONTH, 1);
        }
        //包含最近12个月的每个月的会员总数量
        List<Long> memberCount = new ArrayList<>();


        for (String month : months) {
            //month: 2019-10-31
            month += "-31"; // month = month + "-31";
            long count = memberDao.findCountByMonth(month);
            memberCount.add(count);
        }
        //创建Map，返回所有的数据
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("months", months);
        resultMap.put("memberCount", memberCount);

        return resultMap;
    }
}
